#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>

// 服务器类
class TcpServer : public QTcpServer
{
    Q_OBJECT

public:
    TcpServer(QObject *parent = nullptr) : QTcpServer(parent) {}

protected:
    void incomingConnection(qintptr socketDescriptor) override
    {
        QTcpSocket *socket = new QTcpSocket(this);
        if (!socket->setSocketDescriptor(socketDescriptor))
        {
            qDebug() << "Error setting socket descriptor";
            return;
        }

        connect(socket, &QTcpSocket::readyRead, this, &TcpServer::onReadyRead);
        connect(socket, &QTcpSocket::disconnected, this, &TcpServer::onDisconnected);
    }

public slots:
    void onReadyRead()
    {
        QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
        if (socket)
        {
            QByteArray data = socket->readAll();
            qDebug() << "Server received data: " << data;
        }
    }

    void onDisconnected()
    {
        QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
        if (socket)
        {
            qDebug() << "Server: Socket disconnected";
            socket->deleteLater();
        }
    }
};

// 客户端类
class TcpClient : public QObject
{
    Q_OBJECT

public:
    TcpClient(QObject *parent = nullptr) : QObject(parent)
    {
        socket = new QTcpSocket(this);
        connect(socket, &QTcpSocket::connected, this, &TcpClient::onConnected);
        connect(socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
        connect(socket, &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
    }

public slots:
    void connectToServer()
    {
        socket->connectToHost("127.0.0.1", 12345);  // 替换为实际的服务器地址和端口
    }

    void sendData(const QByteArray &data)
    {
        socket->write(data);
    }

    void onConnected()
    {
        qDebug() << "Client connected to server";
    }

    void onReadyRead()
    {
        QByteArray data = socket->readAll();
        qDebug() << "Client received data: " << data;
    }

    void onDisconnected()
    {
        qDebug() << "Client: Socket disconnected";
    }

private:
    QTcpSocket *socket;
};
